/*
 * Copyright 2012 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.android.apps.mytracks.casos;

import com.doverty.android.maps.mytracks.R;
import com.google.android.apps.mytracks.AbstractMyTracksActivity;
import com.google.android.apps.mytracks.clientes.ClienteDataSource;
import com.google.android.apps.mytracks.clientes.ClientesListActivity;
import com.google.android.apps.mytracks.content.Caso;
import com.google.android.apps.mytracks.content.Investigado;
import com.google.android.apps.mytracks.investigados.InvestigadoDataSource;
import com.google.android.apps.mytracks.investigados.InvestigadosListActivity;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.IntentUtils;
import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtils;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * An activity to add/edit a caso.
 *
 * @author Jimmy Shih
 */
public class CasoEditActivity extends AbstractMyTracksActivity {

  private static final String TAG = CasoEditActivity.class.getSimpleName();

  public static final String EXTRA_TRACK_ID = "track_id";
  public static final String EXTRA_CLIENTE_ID = "cliente_id";
  public static final String EXTRA_CASO_ID = "caso_id";
  public static final String EXTRA_INVESTIGADO1_ID = "investigado1_id";
  public static final String EXTRA_INVESTIGADO2_ID = "investigado2_id";
  public static final String EXTRA_INVESTIGADO3_ID = "investigado3_id";


  private long trackId;
  private long casoId;
  private long clienteId;
  private boolean newCaso;
  private TrackRecordingServiceConnection trackRecordingServiceConnection;
  private CasoDataSource dbCaso;
  private ClienteDataSource dbCliente;
  private InvestigadoDataSource dbInvestigado;
  private Caso caso;
  private List<Investigado> investigados;

  // UI elements
  private EditText casoNombre;
  private TextView casoCliente;
  private TextView casoInvestigado1;
  private TextView nuevoInvestigado1;
  private TextView casoInvestigado2;
  private TextView nuevoInvestigado2;
  private TextView casoInvestigado3;
  private TextView casoFechaComienzo;
  private TextView casoFechaFin;
  private Calendar myCalendar;


  private Button done;

  @Override
  protected void onCreate(Bundle bundle) {
    
    super.onCreate(bundle);
    trackId = getIntent().getLongExtra(EXTRA_TRACK_ID, -1L);
    casoId = getIntent().getLongExtra(EXTRA_CASO_ID, -1L);
    newCaso = casoId == -1L;
    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, null);
    getupUIElements();
    setupUIElements();
    updateUiBycasoId();
  }

  private void getupUIElements() {
    
    casoNombre = (EditText) findViewById(R.id.caso_edit_name);
    casoCliente = (TextView) findViewById(R.id.caso_edit_cliente_info);
    casoInvestigado1 = (TextView) findViewById(R.id.caso_edit_investigado_info1);
    nuevoInvestigado1 = (TextView) findViewById(R.id.caso_edit_investigado_nuevo1);
    casoInvestigado2 = (TextView) findViewById(R.id.caso_edit_investigado_info2);
    nuevoInvestigado2 = (TextView) findViewById(R.id.caso_edit_investigado_nuevo2);
    casoInvestigado3 = (TextView) findViewById(R.id.caso_edit_investigado_info3);
    casoFechaComienzo = (TextView) findViewById(R.id.caso_edit_fecha_comienzo);
    casoFechaFin = (TextView) findViewById(R.id.caso_edit_fecha_fin);


    Button cancel = (Button) findViewById(R.id.caso_edit_cancel);
    cancel.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });
    done = (Button) findViewById(R.id.caso_edit_done);
    done.setText(newCaso ? R.string.generic_add : R.string.generic_save);
  }

  private void setupUIElements() {
    

    casoCliente.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), ClientesListActivity.class);
        intent.putExtra("from", "casoEdit");
        Caso casoCreation = new Caso(
            casoNombre.getText().toString(),
            0, casoFechaComienzo.getText().toString(), casoFechaFin.getText().toString());
        intent.putExtra("caso", casoCreation);
        startActivity(intent);
      }
    });

    casoInvestigado1.addTextChangedListener(new TextWatcher() {

      @Override
      public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (start+count>0)
          nuevoInvestigado1.setVisibility(View.VISIBLE);
        else
          nuevoInvestigado1.setVisibility(View.GONE);
      }
   });
    
    casoInvestigado2.addTextChangedListener(new TextWatcher() {

      @Override
      public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (start+count>0)
          nuevoInvestigado2.setVisibility(View.VISIBLE);
        else
          nuevoInvestigado2.setVisibility(View.GONE);
      }
   });

    casoInvestigado1.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        findViewById(R.id.caso_edit_investigado_info2).setVisibility(View.VISIBLE);
        Intent intent = new Intent(getApplicationContext(), InvestigadosListActivity.class);
        if (getIntent().getExtras()!=null){
          intent.putExtras(getIntent().getExtras());
        }
        intent.putExtra("from", "casoEdit");
        startActivity(intent);
      }
    });
    
    casoInvestigado2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        findViewById(R.id.caso_edit_investigado_info3).setVisibility(View.VISIBLE);
        Intent intent = new Intent(getApplicationContext(), InvestigadosListActivity.class);
        intent.putExtras(getIntent().getExtras());
        startActivity(intent);
      }
    });
    
    casoInvestigado3.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), InvestigadosListActivity.class);
        intent.putExtras(getIntent().getExtras());
        startActivity(intent);
      }
    });
    
    myCalendar = Calendar.getInstance();
    
    final DatePickerDialog.OnDateSetListener dateComienzo = new DatePickerDialog.OnDateSetListener() {

      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
          // TODO Auto-generated method stub
          myCalendar.set(Calendar.YEAR, year);
          myCalendar.set(Calendar.MONTH, monthOfYear);
          myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          updateFechaComienzo();
      }
    };
    
    casoFechaComienzo.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
          new DatePickerDialog(CasoEditActivity.this, dateComienzo, myCalendar
                  .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                  myCalendar.get(Calendar.DAY_OF_MONTH)).show();
      }
    });
    
    final DatePickerDialog.OnDateSetListener dateFin = new DatePickerDialog.OnDateSetListener() {

      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
          // TODO Auto-generated method stub
          myCalendar.set(Calendar.YEAR, year);
          myCalendar.set(Calendar.MONTH, monthOfYear);
          myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          updateFechaFin();
      }
    };
    
    casoFechaFin.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
          new DatePickerDialog(CasoEditActivity.this, dateFin, myCalendar
                  .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                  myCalendar.get(Calendar.DAY_OF_MONTH)).show();
      }
    });
    
    done.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!casoCliente.getText().toString().equals("")){
          if (newCaso) {
            addcaso();
          } else {
            updateCaso();
          }
          Intent intent = IntentUtils.newIntent(CasoEditActivity.this, CasosListActivity.class);
          finish();
          startActivity(intent);
        }
        else{
          Toast.makeText(getApplicationContext(), R.string.caso_add_error_empty_client, Toast.LENGTH_SHORT).show();
        }
      }
    });
  
  }

  private void updateFechaComienzo() {

    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    casoFechaComienzo.setText(sdf.format(myCalendar.getTime()));
    }
  
  private void updateFechaFin() {

    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    casoFechaFin.setText(sdf.format(myCalendar.getTime()));
  }

  @Override
  protected void onStart() {
    super.onStart();
    TrackRecordingServiceConnectionUtils.startConnection(this, trackRecordingServiceConnection);
  }
  
  @Override
  protected void onStop() {
    super.onStop();
    trackRecordingServiceConnection.unbind();
  }

  @Override
  protected int getLayoutResId() {
    return R.layout.caso_edit;
  }

  /**
   * Updates the UI based on the caso id.
   */
  private void updateUiBycasoId() {
  
    setTitle(newCaso ? R.string.menu_insert_caso : R.string.menu_edit);
    
    if (newCaso) {
      Caso casoCreation = (Caso) getIntent().getParcelableExtra("caso");
      if (casoCreation!=null){
        casoNombre.setText(casoCreation.getNombre());
        casoFechaComienzo.setText(casoCreation.getFechaInicio());
        casoFechaFin.setText(casoCreation.getFechaInicio());
        if (casoCreation.getClienteId()!=0){
          casoCliente.setText(getIntent().getStringExtra("nombreCliente"));
        }
      }
    } 
    else {
      dbCaso = new CasoDataSource(this);
      dbCaso.open();
      caso =  dbCaso.getCaso(casoId);
      if (caso == null) {
        Log.d(TAG, "caso is null");
        finish();
        return;
      }
      else{
        clienteId = getIntent().getLongExtra(EXTRA_CLIENTE_ID, -1L);
        dbCliente = new ClienteDataSource(this);
        dbCliente.open();
        if (clienteId == -1L) {
          casoCliente.setText(dbCliente.getCliente(caso.getClienteId()).getNombre());
        }
        else{
          casoCliente.setText(dbCliente.getCliente(clienteId).getNombre());
        }
        dbCliente.close();
        casoNombre.setText(caso.getNombre());
        rellenarInvestigados();
        casoFechaComienzo.setText(caso.getFechaInicio());
        casoFechaFin.setText(caso.getFechaFin());
      }
    }
  }

  private void rellenarInvestigados() {
    
    dbInvestigado = new InvestigadoDataSource(this);
    dbInvestigado.open();
    investigados = dbInvestigado.getAllInvestigadosCaso(casoId);
    if (investigados.size()>0){
      casoInvestigado1.setText(investigados.get(0).getNombre());
      if (investigados.size()>1){
        casoInvestigado2.setText(investigados.get(1).getNombre());
        if (investigados.size()>2){
          casoInvestigado3.setText(investigados.get(2).getNombre());
         }
       }
     }
  }
  
  /**
   * Adds a case.
   */
  private void addcaso() {
    
    dbCaso = new CasoDataSource(this);
    dbCaso.open();
    long idCliente = getIntent().getLongExtra(EXTRA_CLIENTE_ID, -1L);
    Caso casoCreation = new Caso(
        casoNombre.getText().toString(),
        idCliente, casoFechaComienzo.getText().toString(), casoFechaFin.getText().toString());
    long insertCasoId = dbCaso.createCaso(casoCreation);
    
    long investigado1 = getIntent().getLongExtra(EXTRA_INVESTIGADO1_ID, -1L);
    if (investigado1 != -1L){
         dbInvestigado.addCasoInvestigado(investigado1, insertCasoId);
    }

    long investigado2 = getIntent().getLongExtra(EXTRA_INVESTIGADO2_ID, -1L);
    if (investigado2 != -1L){
         dbInvestigado.addCasoInvestigado(investigado2, insertCasoId);
    }
    
    long investigado3 = getIntent().getLongExtra(EXTRA_INVESTIGADO3_ID, -1L);
    if (investigado3 != -1L){
         dbInvestigado.addCasoInvestigado(investigado3, insertCasoId);
    }
    
    Toast.makeText(this, R.string.caso_add_success, Toast.LENGTH_SHORT).show();
  }

  /**
   * update a caso.
   */
  private void updateCaso() {
    
    long clienteid = getIntent().getLongExtra(EXTRA_CLIENTE_ID, -1L);
    if (clienteid != -1L){
      Caso casoCreation = new Caso(casoId,
          casoNombre.getText().toString(),
          clienteid,
          casoFechaComienzo.getText().toString(), 
          casoFechaFin.getText().toString());
      dbCaso.updateCaso(casoCreation);
    }
    updateInvestigados();
  }
  
  private void updateInvestigados(){
    
    /*if (telefonosCaso.size()>0){
      if((telefonosCaso.get(0).getNumero()!=casoTelefono1.getText().toString() || 
          telefonosCaso.get(0).getTipo()!=casoTelefonoTipo1.getSelectedItem().toString())){
        TelefonoCaso telefonoCasoCreation = new TelefonoCaso(telefonosCaso.get(0).getId(),
            casoId,casoTelefono1.getText().toString(), casoTelefonoTipo1.getSelectedItem().toString());
        dbTelefonoCaso.updateTelefonoCaso(telefonoCasoCreation);
      }
      if (telefonosCaso.size()>1){
        if((telefonosCaso.get(1).getNumero()!=casoTelefono2.getText().toString() || 
            telefonosCaso.get(1).getTipo()!=casoTelefonoTipo2.getSelectedItem().toString())){
          TelefonoCaso telefonoCasoCreation = new TelefonoCaso(telefonosCaso.get(1).getId(),
              casoId,casoTelefono2.getText().toString(), casoTelefonoTipo2.getSelectedItem().toString());
          dbTelefonoCaso.updateTelefonoCaso(telefonoCasoCreation);
        }
        if (telefonosCaso.size()>2){
          if((telefonosCaso.get(2).getNumero()!=casoTelefono3.getText().toString() || 
              telefonosCaso.get(2).getTipo()!=casoTelefonoTipo3.getSelectedItem().toString())){
            TelefonoCaso telefonoCasoCreation = new TelefonoCaso(telefonosCaso.get(2).getId(),
                casoId,casoTelefono3.getText().toString(), casoTelefonoTipo3.getSelectedItem().toString());
            dbTelefonoCaso.updateTelefonoCaso(telefonoCasoCreation);
          }
        }
        else{
          if (!(casoTelefono3.getText().toString().equals(""))){
            TelefonoCaso telefonoCasoCreation2 = new TelefonoCaso(casoId,
            casoTelefono3.getText().toString(),
            casoTelefonoTipo3.getSelectedItem().toString());
            dbTelefonoCaso.createTelefonoCaso(telefonoCasoCreation2);
            }
        }
      }
      else{
        if (!(casoTelefono2.getText().toString().equals(""))){
          TelefonoCaso telefonoCasoCreation2 = new TelefonoCaso(casoId,
          casoTelefono2.getText().toString(),
          casoTelefonoTipo2.getSelectedItem().toString());
          dbTelefonoCaso.createTelefonoCaso(telefonoCasoCreation2);
        }
      }
    }
    else{
      if (!(casoTelefono1.getText().toString().equals(""))){
        TelefonoCaso telefonoCasoCreation = new TelefonoCaso(casoId,
        casoTelefono1.getText().toString(),
        casoTelefonoTipo1.getSelectedItem().toString());
        dbTelefonoCaso.createTelefonoCaso(telefonoCasoCreation);
      }

      if (!(casoTelefono2.getText().toString().equals(""))){
        TelefonoCaso telefonoCasoCreation2 = new TelefonoCaso(casoId,
        casoTelefono2.getText().toString(),
        casoTelefonoTipo2.getSelectedItem().toString());
        dbTelefonoCaso.createTelefonoCaso(telefonoCasoCreation2);
      }
      
      if (!(casoTelefono3.getText().toString().equals(""))){
        TelefonoCaso telefonoCasoCreation3 = new TelefonoCaso(casoId,
        casoTelefono3.getText().toString(),
        casoTelefonoTipo3.getSelectedItem().toString());
        dbTelefonoCaso.createTelefonoCaso(telefonoCasoCreation3);
      }
    }*/
  }
}
